package server.fsm;

import etc.SynchronizationParameters;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import lib.Base64;

public class UploadingState extends GenericServerState {

	private String relativeFilePathAndName = null;

	private File sourceFile = null;

	private FileInputStream inFromFile = null;

	private int chunkSize = 0;

	private long localWaitingBytes = 0,
			remoteWaitingBytes = 0;

	public UploadingState( String file, Long size, int chunkSize ) throws FileNotFoundException {
		this.relativeFilePathAndName = file;
		this.sourceFile = new File( SynchronizationParameters.getLocalPath() + '\\' + file.replace('/', '\\') );
		this.inFromFile = new FileInputStream( sourceFile );

		this.remoteWaitingBytes = size;
		this.localWaitingBytes = sourceFile.length();
		this.chunkSize = chunkSize;
	}

	@Override
	public String waiting( String file, Long size ) {
		try {
			remoteWaitingBytes = size;

			if( (sourceFile != null) && (inFromFile != null)
					&& (remoteWaitingBytes == localWaitingBytes) ) {
				
				byte[] sendBuffer = new byte[chunkSize];
				int sentBytes = inFromFile.read( sendBuffer );
				String encodedData = Base64.encodeBytes( sendBuffer, 0, sentBytes );

				remoteWaitingBytes -= sentBytes;
				localWaitingBytes -= sentBytes;
				
				return "<data>" + encodedData + "</data>";
			}
		} catch (IOException ex) {}

		return "<error type='IO_ERROR'>An error occured while reading or sending the file on server.</error>";
	}

	@Override
	public String receive( Boolean didFail ) {
		try {
			inFromFile.close();
		} catch (IOException ex) {}
		sourceFile = null;
		
		if( didFail ) {
			getServerContext().setCurrentServerState( new AuthorizedState(), "Could not upload file '"+relativeFilePathAndName+"'." );
		}else{
			getServerContext().setCurrentServerState( new AuthorizedState(), "Uploaded file '"+relativeFilePathAndName+"'." );
		}
		return null;
	}

	@Override
	public String logout() {
		try {
			inFromFile.close();
		} catch (IOException ex) {}
		sourceFile = null;

		getServerContext().setCurrentServerState( new WaitingState(), "Client logged out, waiting for re-authorization." );
		return "<logout result='OK'>You have logged out from the server.</logout>";
	}
	
}
